﻿/*
 * ©2009-2010 XELF
 * http://xelf.info
 */

using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace XELF.Framework {

	public unsafe struct Int32Text {
		const int Length = 11;
		int index;
		fixed char digits[Length];

		public Int32Text(int value) {
			index = 0;
			AddValue(value, 0, ' ');
		}
		public Int32Text(int value, int numbderDigits, char padding) {
			index = 0;
			AddValue(value, numbderDigits , padding);
		}
		void AddValue(int value, int numberDigits, char padding) {
			bool negative;
			if (value >= 0) {
				value = -value;
				negative = false;
			} else {
				negative = true;
			}
			do {
				var next = value / 10;
				var remain = value - next * 10;
				Add((char)('0' - remain));
				value = next;
			} while (value != 0);
			for (int i = index + (negative ? 1 : 0); i < numberDigits; i++) {
				Add(padding);
			}
			if (negative) Add('-');
		}
		void Add(char value) {
			index++;
			fixed (char* p = digits) {
				p[Length - index] = value;
			}
		}
		public void AppendTo(StringBuilder text) {
			fixed (char* p = digits) {
				for (int i = Length - index; i < Length; i++) {
					text.Append(p[i]);
				}
			}
		}
	}

	public static partial class Helper {
		public static void AppendCustom(this StringBuilder text, int value) {
			new Int32Text(value).AppendTo(text);
		}
		public static void AppendCustom(this StringBuilder text, int value, int numberDigits, char padding) {
			new Int32Text(value, numberDigits, padding).AppendTo(text);
		}
	}

}
